<?php

/**
 *
 * @author lovebing <lovebing365@126.com> Created on 2015-5-4
 */
class WechatPaymentCenter {
    const BASE_URL_PAY = 'http://%s/wechatpay/start/';
    const BASE_URL_RETURN = 'http://%s/';

    private $appid;
    private $key;
    private $mchid;
    private $orderNoPrefix = '';
    
    private $lastPaymentId = 0;

    private $comId = 0;
    private $wechatSettingModel = null;


    /**
     * 
     * @param type $comId
     * @param type $appid
     * @param type $key
     * @param type $mchid
     */
    public function __construct($comId, $appid, $key, $mchid) {
        $this->appid = $appid;
        $this->key = $key;
        $this->mchid = $mchid; 
        $this->comId = $comId;
        $this->wechatSettingModel = WechatSetting::findById($comId);
    }
    
    /**
     * 
     * @param type $prefix
     */
    public function setOrderNoPrefix($prefix) {
        $this->orderNoPrefix = $prefix;
    }
    
    /**
     * 
     * @param type $orderNo
     * @param type $totalfee
     * @param type $openid
     * @param type $paymentDesc
     * @param type $returnUrl
     * @param type $notifyUrl
     * @return type
     */
    public function createPayment($orderNo, $totalfee, $openid, $paymentDesc, $returnUrl, $notifyUrl) {
        $model = new PaymentWechatModel();
        $model->mp_appid = $this->appid;
        $model->mp_key = $this->key;
        $model->mp_mchid = $this->mchid;
        $model->order_number = $this->orderNoPrefix.$orderNo;
        $model->totalfee = $totalfee * 100;
        
        $model->openid = $openid;
        $model->payment_desc = $paymentDesc;
        
        $model->notify_url =$notifyUrl;
        $model->return_url = $returnUrl;
        $model->create_time = date('Y-m-d H:i:s');
        
        if(!$model->save()) {
            throw new RuntimeException($model->getFirstErrorDesc());
        }
        
        $this->lastPaymentId = $model->id;
        return $model->id;
    }
 
    
    /**
     * 
     * @param type $id
     * @return type
     */
    public function getPayUrl($id = null) {
        if(is_null($id)) {
            $id = $this->lastPaymentId;
        }
        return sprintf(self::BASE_URL_PAY, $this->wechatSettingModel->getPaymentDomain()).$id;
    }
    
    /**
     * 
     * @return type
     */
    public function getLastPaymentId() {
        return $this->lastPaymentId;
    }

    /**
     * 
     * @param type $path
     * @return type
     */
    public function getReturnUrl($path) {
        return sprintf(self::BASE_URL_RETURN, $this->wechatSettingModel->getMobileDomain()).$path;
    }
}
